//
//  PlayerItem.m
//  ImGuider
//
//  Created by 王鹏宇 on 2017/4/13.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "PlayerItem.h"
#import "ScenicPlayVC.h"
#import "CityTourPlay.h"
#import "SpecialPlayVC.h"
#import "BasePlayVC.h"
#import "CityTourListVC.h"
#define PlayItemLineModel  @"PlayItemLineModel"
#define PlayItemCurremtPoint  @"PlayItemCurremtPoint"
#import "IGAvPlayerManager.h"
#import "ScenicNodePlayVC.h"

@interface PlayerItem()
@property (nonatomic, strong) UIImageView *bgImageView;

@end

@implementation PlayerItem


+ (instancetype)playItemShareManager{
    
    static PlayerItem *manager;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] initWithFrame:CGRectMake(kScreenWidth - 50,kNavigationBarHeight - 44, 44, 44)];
        
    });
    return manager;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
       
        [self setup];
    }
    return self;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setup];
    }
    return self;
}

- (void)setLineModel:(LineModel *)lineModel {
    
    [[NSUserDefaults standardUserDefaults] setObject:[lineModel modelToJSONString] forKey:PlayItemLineModel];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
}

- (LineModel *)lineModel {
    
    NSString *linemodelJson = [[NSUserDefaults standardUserDefaults] objectForKey:PlayItemLineModel];
    
    return [LineModel modelWithJSON:linemodelJson];
    
}

- (void)setPoint:(ScenicPoint *)point {
    
    [self.bgImageView setImageURL:[NSURL URLWithString:point.pictureArray.firstObject] placeholderImage:nil];
    
    [[NSUserDefaults standardUserDefaults] setObject:[point modelToJSONString] forKey:PlayItemCurremtPoint];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (ScenicPoint *)point {
    
    NSString *scenicPointJson = [[NSUserDefaults standardUserDefaults] objectForKey:PlayItemCurremtPoint];
    
    return [ScenicPoint modelWithJSON:scenicPointJson];
}

- (void)setup{
   
    
    self.bgImageView = [[UIImageView alloc] init];
    self.bgImageView.clipsToBounds = YES;
    self.bgImageView.layer.cornerRadius = 15;
    self.bgImageView.contentMode = UIViewContentModeScaleAspectFill;
    [self addSubview:self.bgImageView];
    [self.bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.equalTo(self.mas_centerX);
        make.centerY.equalTo(self.mas_centerY);
        make.width.height.mas_equalTo(30);
    }];
    
    
    self.iconImageView = [[UIImageView alloc] initWithImage: [UIImage imageNamed:@"flowPlay"]];
    
    [self addSubview:self.iconImageView];
    
    
    self.backgroundColor = [UIColor clearColor];
    [self.iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.mas_centerX);
        make.centerY.equalTo(self.mas_centerY);
    }];
    
    self.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(reback:)];
    [self addGestureRecognizer:tap];
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(playAnimation) userInfo:nil repeats:YES];
    [self.timer setFireDate:[NSDate distantFuture]];
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode: NSRunLoopCommonModes];
    self.tag = 1024;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(PlayerItemChangePlayWith:) name:kIGAvPlayerManagerState object:nil];
    
    if (self.point) {
        
        [self.bgImageView setImageURL:[NSURL URLWithString:self.point.pictureArray.firstObject] placeholderImage:nil];
    }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)playAnimation {
    
    self.iconImageView.transform = CGAffineTransformRotate(self.iconImageView.transform, M_PI_4 /5);
}

- (void)startAnimation {
    
    [self.timer setFireDate:[NSDate distantPast]];
    self.isItemPlay = YES;
}

- (void)stopAnimation {
    
    [self.timer setFireDate:[NSDate distantFuture]];
    self.iconImageView.transform = CGAffineTransformIdentity;
    self.isItemPlay = NO;
}

- (void)reback:(UITapGestureRecognizer *)tap
{
    
    if (self.lineModel && self.point) {
        [self goPlayVC];
    }else {
        
        
        UIViewController * currentVC = [IGUtil currentViewController] ;
        
        CityTourListVC *vc = [CityTourListVC new];
        vc.isItemAction = YES;
        vc.isPopular = YES;
        vc.hidesBottomBarWhenPushed = YES;
        [currentVC.navigationController pushViewController:vc animated:YES];
    }
    
}

- (void)goPlayVC {
    
    UIViewController * currentVC = [IGUtil currentViewController] ;
    for (UIViewController *vc in currentVC.navigationController.viewControllers) {
        
        if ([vc isKindOfClass:[BasePlayVC class]]) {
            [currentVC.rt_navigationController removeViewController:vc];
        }
    }
    
    BasePlayVC * playVC;
    
    switch (self.lineModel.type.integerValue) {
        case 1:
        {
            
            playVC = [[CityTourPlay alloc] init];
            playVC.pageType = 2;
        }
            break;
        case 2:
        case 3:
        {
            if (self.lineModel.hascode.integerValue > 0) {
                playVC = [[ScenicNodePlayVC alloc] init];
                playVC.isItemIn = YES;
            }else {
                playVC = [[ScenicPlayVC alloc] init];
                playVC.pageType = 2;
            }
            
            
            
        }
            break;
        case 4:
        {
            playVC = [IGUtil loadViewController:@"SpecialPlayVC" storyboard:@"SpecialPlayVC"];
        }
            break;
            
        default:
            break;
    }
   // PlayerItem * item = [PlayerItem playItemShareManager];
    
    if ([IGAvPlayerManager shareManeger].playType == PlayLine ||[IGAvPlayerManager shareManeger].playType == PlaySpecial ) {
       
    }else {
        [[IGAvPlayerManager shareManeger] stop];
    }
    playVC.hidesBottomBarWhenPushed = YES;
    playVC.currentScenicPoint = self.point;
    playVC.lineModel = self.lineModel;
    
    [currentVC.navigationController pushViewController:playVC animated:YES];
}
- (void)show{
    
    if (![[UIApplication sharedApplication].keyWindow viewWithTag:1024]) {
         [[UIApplication sharedApplication].keyWindow addSubview:self];
    }
    
    [[UIApplication sharedApplication].keyWindow bringSubviewToFront:self];
    self.hidden = NO;
}

- (void)hide{
    
//    if ([[UIApplication sharedApplication].keyWindow viewWithTag:1024]) {
//    }
    self.hidden = YES;
}

//- (void)pan:(UIPanGestureRecognizer *)pan
//{
//    CGPoint point = [pan locationInView:[UIApplication sharedApplication].keyWindow];
//    PlayerItem *view = (PlayerItem *)pan.view;
//
//    CGFloat distance = 40;  // 离四周的最小边距
//
//    if (pan.state == UIGestureRecognizerStateEnded) {
//
//
//        if (point.y <= distance) {
//
//            point.y = distance;
//
//        }else if (point.y >= [UIScreen mainScreen].bounds.size.height - distance){
//
//            point.y = [UIScreen mainScreen].bounds.size.height - distance;
//        }else if (point.x <= [UIScreen mainScreen].bounds.size.width/2.0) {
//
//            point.x = distance;
//
//        }else {
//
//            point.x = [UIScreen mainScreen].bounds.size.width - distance;
//        }
//
//        [UIView animateWithDuration:0.5 animations:^{
//            view.center = point;
//
//        }];
//
//    }else {
//
//        view.center = point;
//    }
//
//}




- (void)PlayerItemChangePlayWith:(NSNotification *)notif
{
    NSInteger state = [notif.userInfo[kIGAvPlayerManagerState] integerValue];
    NSNumber * type = notif.userInfo[kPlayType];
    if (type.integerValue != PlayLine && type.integerValue != PlaySpecial) {
        
        if (self.isItemPlay) {
            [self stopAnimation];
        }
        return;
    }
    switch (state) {
        case AVPlayerPlayStatePreparing:
        case AVPlayerPlayStateBeigin:
        case AVPlayerPlayStatePlaying:
        {
            if (!self.isItemPlay) {
                [self startAnimation];
            }
        }
            break;
        case AVPlayerPlayStatePause:
        case AVPlayerPlayStateEnd:
        case AVPlayerPlayStateNotPlay:
        case AVPlayerPlayStateNotKnow:
        {
            if (self.isItemPlay) {
                [self stopAnimation];
            }
        }
            break;
        default:
        {
           
            [self stopAnimation];
            self.isItemPlay = NO;
        }
            break;
    }
    
}

@end
